package au.com.bus4u.service.impl;

import au.com.bus4u.Bus4uApplication;
import au.com.bus4u.dao.DaoSupport;
import au.com.bus4u.exception.ServiceException;
import au.com.bus4u.service.AuctionService;
import au.com.bus4u.service.OrderService;
import au.com.bus4u.utils.*;
import lombok.extern.java.Log;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.ScheduledFuture;

@Service("orderService")
@Log
public class OrderServiceImpl implements OrderService {

    @Autowired
    private DaoSupport daoSupport;
    @Autowired
    private AuctionService auctionService;
    private String mapper = "OrderMapper.";


    @Override
    public int save(PageData pd) throws Exception {
        //游客新增订单非空验证
        checkUserInfo(pd);

        //新增订单填入默认值
        pd = addOrderDefaultValue(pd);

        if(pd.get("stop[0][stop]")!=null && !"".equals(pd.get("stop[0][stop]"))){
            pd.put("stop1",pd.get("stop[0][stop]"));
        }
        if(pd.get("stop[1][stop]")!=null && !"".equals(pd.get("stop[1][stop]"))){
            pd.put("stop2",pd.get("stop[1][stop]"));
        }
        if(pd.get("stop[2][stop]")!=null && !"".equals(pd.get("stop[2][stop]"))){
            pd.put("stop3",pd.get("stop[2][stop]"));
        }
        if(pd.get("stop[3][stop]")!=null && !"".equals(pd.get("stop[3][stop]"))){
            pd.put("stop4",pd.get("stop[3][stop]"));
        }
        if(pd.get("stop[4][stop]")!=null && !"".equals(pd.get("stop[4][stop]"))){
            pd.put("stop5",pd.get("stop[4][stop]"));
        }
        return (int) daoSupport.save(mapper+"save", pd);
    }


    @Override
    @Transactional
    public int edit(PageData pd) throws Exception {

        //检查修改数据中是否包含订单竞拍时间范围字段auction_range_time,如果有执行定时任务将竞拍状态有状态竞拍中修改为竞拍结束
        pd = checkOrderStatus(pd);
        pd = checkOrderData(pd);

//        pd.remove("order_status");//测试关闭状态修改
        if(pd.get("stop[0][stop]")!=null && !"".equals(pd.get("stop[0][stop]"))){
            pd.put("stop1",pd.get("stop[0][stop]"));
        }
        if(pd.get("stop[1][stop]")!=null && !"".equals(pd.get("stop[1][stop]"))){
            pd.put("stop2",pd.get("stop[1][stop]"));
        }
        if(pd.get("stop[2][stop]")!=null && !"".equals(pd.get("stop[2][stop]"))){
            pd.put("stop3",pd.get("stop[2][stop]"));
        }
        if(pd.get("stop[3][stop]")!=null && !"".equals(pd.get("stop[3][stop]"))){
            pd.put("stop4",pd.get("stop[3][stop]"));
        }
        if(pd.get("stop[4][stop]")!=null && !"".equals(pd.get("stop[4][stop]"))){
            pd.put("stop5",pd.get("stop[4][stop]"));
        }

        return (int) daoSupport.update(mapper+"edit", pd);
    }

    /**
     * 效验订单状态
     * 检查修改数据中是否包含订单竞拍时间范围字段auction_range_time,如果有执行定时任务将竞拍状态有状态竞拍中修改为竞拍结束
     * @param pd
     * @return
     */
    private PageData checkOrderStatus(PageData pd) {
        if(pd.get("auction_range_time") != null && !"".equals(pd.getString("auction_range_time"))){
            String auction_range_time_str = pd.getString("auction_range_time");
//            System.err.println("auction_range_time = " + auction_range_time_str);

            //计算订单竞拍结束时间，写入数据库
            Integer auction_range_time = 0;
            try {
                auction_range_time = Integer.parseInt(auction_range_time_str);
            } catch (NumberFormatException e) {
                throw new ServiceException("竞拍时间范围数据错误:请输入大于0的整数数字!");
            }
            if(auction_range_time <= 0 ){
                throw new ServiceException("竞拍时间范围数据错误:请输入大于0的整数数字!");
            }
            Date newDate = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(newDate);

//            calendar.add(Calendar.HOUR, auction_range_time);//当前时间+ auction_range_time 小时
            calendar.add(Calendar.MINUTE, auction_range_time);//当前时间+ auction_range_time 分钟


            Date auction_over_time = calendar.getTime();
            pd.put("auction_over_time",auction_over_time);
            pd.put("order_status",4);

//            System.err.println("当前时间 = " + DateUtil.formatDate(newDate,"yyyy-MM-dd HH:mm"));
//            System.err.println("竞拍结束时间 = " + DateUtil.formatDate(auction_over_time,"yyyy-MM-dd HH:mm"));

            //开启多线程定时器任务 执行 超过竞拍时间范围后自动将竞拍状态由竞拍中改为 竞拍结束后的 1.竞拍成功-待支付 2.竞拍失败-流拍
            //开启多线程方法 startNewThreadRunAuctionOver()
            Integer order_id = pd.getInt("order_id");
            startNewThreadRunAuctionOver(auction_over_time,order_id);
        }



        return pd;
    }

    private PageData checkOrderData(PageData pd) {
        if(pd.get("order_id") ==null|| "".equals(pd.get("order_id").toString()) ){
            throw new ServiceException("订单更新失败:order_id不能空");
        }
        if(pd.get("order_prefix_name") ==null|| "".equals(pd.get("order_prefix_name").toString()) ){
            pd.remove("order_prefix_name");
        }
        if(pd.get("user_id") ==null|| "".equals(pd.get("user_id").toString()) ){
            pd.remove("user_id");
        }
        if(pd.get("order_type") ==null|| "".equals(pd.get("order_type").toString()) ){
            pd.remove("order_type");
        }
        if(pd.get("passengers") ==null|| "".equals(pd.get("passengers").toString()) ){
            pd.remove("passengers");
        }
        if(pd.get("driver_phone") ==null|| "".equals(pd.get("driver_phone").toString()) ){
            pd.remove("driver_phone");
        }
        if(pd.get("contact_phone") ==null|| "".equals(pd.get("contact_phone").toString()) ){
            pd.remove("contact_phone");
        }
        if(pd.get("other_contact_phone") ==null|| "".equals(pd.get("other_contact_phone").toString()) ){
            pd.remove("other_contact_phone");
        }
        if(pd.get("contact_email") ==null|| "".equals(pd.get("contact_email").toString()) ){
            pd.remove("contact_email");
        }
        if(pd.get("other_contact_email") ==null|| "".equals(pd.get("other_contact_email").toString()) ){
            pd.remove("other_contact_email");
        }
        if(pd.get("time_depart") ==null|| "".equals(pd.get("time_depart").toString()) ){
            pd.remove("time_depart");
        }
        if(pd.get("stop1") ==null|| "".equals(pd.get("stop1").toString()) ){
            pd.remove("stop1");
        }
        if(pd.get("stop2") ==null|| "".equals(pd.get("stop2").toString()) ){
            pd.remove("stop2");
        }
        if(pd.get("stop3") ==null|| "".equals(pd.get("stop3").toString()) ){
            pd.remove("stop3");
        }
        if(pd.get("stop4") ==null|| "".equals(pd.get("stop4").toString()) ){
            pd.remove("stop4");
        }
        if(pd.get("stop5") ==null|| "".equals(pd.get("stop5").toString()) ){
            pd.remove("stop5");
        }
        if(pd.get("towhere") ==null|| "".equals(pd.get("towhere").toString()) ){
            pd.remove("towhere");
        }
        if(pd.get("time_return") ==null|| "".equals(pd.get("time_return").toString()) ){
            pd.remove("time_return");
        }
        if(pd.get("est_time_needed") ==null|| "".equals(pd.get("est_time_needed").toString()) ){
            pd.remove("est_time_needed");
        }
        if(pd.get("hours_day") ==null|| "".equals(pd.get("hours_day").toString()) ){
            pd.remove("hours_day");
        }
        if(pd.get("custo_sum") ==null|| "".equals(pd.get("custo_sum").toString()) ){
            pd.remove("custo_sum");
        }
        if(pd.get("vehicle_type") ==null|| "".equals(pd.get("vehicle_type").toString()) ){
            pd.remove("vehicle_type");
        }
        if(pd.get("vehicle_plate") ==null|| "".equals(pd.get("vehicle_plate").toString()) ){
            pd.remove("vehicle_plate");
        }
        if(pd.get("server_user_id") ==null|| "".equals(pd.get("server_user_id").toString()) ){
            pd.remove("server_user_id");
        }
        if(pd.get("auction_price") ==null|| "".equals(pd.get("auction_price").toString()) ){
            pd.remove("auction_price");
        }
        if(pd.get("server_user_name") ==null|| "".equals(pd.get("server_user_name").toString()) ){
            pd.remove("server_user_name");
        }
        if(pd.get("custo_costs") ==null|| "".equals(pd.get("custo_costs").toString()) ){
            pd.remove("custo_costs");
        }
        if(pd.get("flight_id") ==null|| "".equals(pd.get("flight_id").toString()) ){
            pd.remove("flight_id");
        }
        if(pd.get("big_luggage") ==null|| "".equals(pd.get("big_luggage").toString()) ){
            pd.remove("big_luggage");
        }
        if(pd.get("carry_luggage") ==null|| "".equals(pd.get("carry_luggage").toString()) ){
            pd.remove("carry_luggage");
        }
        if(pd.get("babyseats_s") ==null|| "".equals(pd.get("babyseats_s").toString()) ){
            pd.remove("babyseats_s");
        }
        if(pd.get("babyseats_b") ==null|| "".equals(pd.get("babyseats_b").toString()) ){
            pd.remove("babyseats_b");
        }
        if(pd.get("trailer") ==null|| "".equals(pd.get("trailer").toString()) ){
            pd.remove("trailer");
        }
        if(pd.get("toll") ==null|| "".equals(pd.get("toll").toString()) ){
            pd.remove("toll");
        }
        if(pd.get("GST") ==null|| "".equals(pd.get("GST").toString()) ){
            pd.remove("GST");
        }
        if(pd.get("WH_with") ==null|| "".equals(pd.get("WH_with").toString()) ){
            pd.remove("WH_with");
        }
        if(pd.get("WH_OnBoard") ==null|| "".equals(pd.get("WH_OnBoard").toString()) ){
            pd.remove("WH_OnBoard");
        }
        if(pd.get("order_voucher") ==null|| "".equals(pd.get("order_voucher").toString()) ){
            pd.remove("order_voucher");
        }
        if(pd.get("driver_DM") ==null|| "".equals(pd.get("driver_DM").toString()) ){
            pd.remove("driver_DM");
        }
        if(pd.get("extra_request") ==null|| "".equals(pd.get("extra_request").toString()) ){
            pd.remove("extra_request");
        }
        if(pd.get("pay_type") ==null|| "".equals(pd.get("pay_type").toString()) ){
            pd.remove("pay_type");
        }
        if(pd.get("reject") ==null|| "".equals(pd.get("reject").toString()) ){
            pd.remove("reject");
        }
        if(pd.get("auction_range_time") ==null|| "".equals(pd.get("auction_range_time").toString()) ){
            pd.remove("auction_range_time");
        }
        if(pd.get("APF") ==null|| "".equals(pd.get("APF").toString()) ){
            pd.remove("APF");
        }
        if(pd.get("NPEF") ==null|| "".equals(pd.get("NPEF").toString()) ){
            pd.remove("NPEF");
        }
        if(pd.get("Invoice") ==null|| "".equals(pd.get("Invoice").toString()) ){
            pd.remove("Invoice");
        }


        if(pd.get("order_status") ==null|| "".equals(pd.get("order_status").toString()) ){
            pd.remove("order_status");
        }
        if(pd.get("order_status_name") ==null|| "".equals(pd.get("order_status_name").toString()) ){
            pd.remove("order_status_name");
        }
        if(pd.get("contact_name") ==null|| "".equals(pd.get("contact_name").toString()) ){
            pd.remove("contact_name");
        }
        if(pd.get("fromwhere") ==null|| "".equals(pd.get("fromwhere").toString()) ){
            pd.remove("fromwhere");
        }
        if(pd.get("towhere") ==null|| "".equals(pd.get("towhere").toString()) ){
            pd.remove("towhere");
        }



        if(pd.get("time_return") ==null|| "".equals(pd.get("time_return").toString()) ){
            pd.remove("time_return");
        }
        if(pd.get("auction_over_time") ==null|| "".equals(pd.get("auction_over_time").toString()) ){
            pd.remove("auction_over_time");
        }
        if(pd.get("reject_time") ==null|| "".equals(pd.get("reject_time").toString()) ){
            pd.remove("reject_time");
        }
        if(pd.get("pay_time") ==null|| "".equals(pd.get("pay_time").toString()) ){
            pd.remove("pay_time");
        }
        if(pd.get("add_time") ==null|| "".equals(pd.get("add_time").toString()) ){
            pd.remove("add_time");
        }
        if(pd.get("auction_over_time") ==null|| "".equals(pd.get("auction_over_time").toString()) ){
            pd.remove("auction_over_time");
        }
        if(pd.get("auction_over_time") ==null|| "".equals(pd.get("auction_over_time").toString()) ){
            pd.remove("auction_over_time");
        }
        if(pd.get("auction_over_time") ==null|| "".equals(pd.get("auction_over_time").toString()) ){
            pd.remove("auction_over_time");
        }
        if(pd.get("auction_over_time") ==null|| "".equals(pd.get("auction_over_time").toString()) ){
            pd.remove("auction_over_time");
        }
        if(pd.get("auction_over_time") ==null|| "".equals(pd.get("auction_over_time").toString()) ){
            pd.remove("auction_over_time");
        }
        if(pd.get("auction_over_time") ==null|| "".equals(pd.get("auction_over_time").toString()) ){
            pd.remove("auction_over_time");
        }
        if(pd.get("auction_over_time") ==null|| "".equals(pd.get("auction_over_time").toString()) ){
            pd.remove("auction_over_time");
        }

        return pd;
    }

    @Autowired
    private DynamicTask task;
    /**
     * 开启多线程方法
     * 开启多线程定时器任务
     * 执行 超过竞拍时间范围后自动将竞拍状态由竞拍中改为 竞拍结束后的
     *      1.竞拍成功-待支付
     *      2.竞拍失败-流拍
     */
    private void startNewThreadRunAuctionOver(Date auction_over_time,Integer order_id){
//        System.err.println("定时任务开始时间:" + DateUtil.formatDate(new Date(),"yyyy-MM-dd HH:mm:ss"));
        String threadName = Thread.currentThread().getName();

//        String cron = "1 1 2 * * ? *";//秒、分、时、天、月、星期、年
        String s = DateUtil.formatDate(auction_over_time, "s");
        String m = DateUtil.formatDate(auction_over_time, "m");
        String H = DateUtil.formatDate(auction_over_time, "H");

        String cron = s+" "+m+" "+H+" * * ?";
//        System.err.println("cron = " + cron);
        RunAuctionOverTask runAuctionOverTask = new RunAuctionOverTask(threadName,order_id);
        CronTrigger cronTrigger = new CronTrigger(cron);

        //开启多线程定时程序  传递参数 线程名称threadName 执行程序Runnable 触发器CronTrigger 
        task.startCron(threadName,runAuctionOverTask,cronTrigger);
    }

    private class RunAuctionOverTask implements Runnable {
        private String threadName;
        private Integer order_id;
        RunAuctionOverTask(String threadName,Integer order_id) {
            this.threadName = threadName;
            this.order_id = order_id;
        }
        @Override
        public void run() {

//            System.err.println("线程任务:" + threadName+" ，被执行了");
//            System.err.println("定时任务执行时间:" + DateUtil.formatDate(new Date(),"yyyy-MM-dd HH:mm:ss"));
            
            //重新从数据库订单表中获取 该订单的订单状态 如果状态不是竞拍中 则说明管理员已经处理 无需再执行任何操作修改 如果还是竞拍中的状态
            Integer order_status;
            try {
                order_status = (Integer)daoSupport.findForObject(mapper + "findStatusByOrderId", order_id);
//                System.err.println("重新从数据库中获取订单状态 order_status = " + order_status);
                if(order_status!=null && 4 == order_status){
                    //超过竞拍时间范围后自动将竞拍状态由【竞拍中】改为 竞拍结束后的

                    //通过订单id到竞拍表中 获取竞拍数据
                    PageData minAuctionAmount = (PageData) daoSupport.findForObject("AuctionMapper.findMinAuctionAmountById",order_id);
//                    List<PageData> minAuctionAmount = (List<PageData>) daoSupport.findForList("AuctionMapper.findMinAuctionAmountById",order_id);
//                    System.err.println("最低竞拍价格 = " + minAuctionAmount.get("auction_amount"));

                    PageData update = new PageData();
                    update.put("order_id",order_id);
                    if(minAuctionAmount!=null){
                        String auction_amount = minAuctionAmount.get("auction_amount").toString();

                         /*
                            一.竞拍成功-【待支付】
                                获取竞拍数据 如果有人参与竞拍 则将执行竞拍成功操作
                                    1.将订单状态修改为待支付
                                    2.竞拍出价最低的设置为竞拍成功的人
                                    3.计算游客需支付费用
                                    3.发送邮件通知游客支付
                         */

                        //执行更新auction表前 需将该订单下的所有竞拍数据has_success重置为0 避免重复确认竞拍成功人的bug  clearAuctionSuccess
                        auctionService.clearAuctionSuccess(order_id);

//                        System.err.println("订单(order_id:"+order_id+")竞拍时间结束:竞拍成功");
                        minAuctionAmount.put("has_success",1);//竞拍是否成功 0-不成功 1成功
                        daoSupport.update("AuctionMapper.editByAuctionId",minAuctionAmount);//竞拍出价最低的设置为竞拍成功的人

                        update.put("order_status",6);//将订单状态修改为待支付
                        update.put("auction_price",auction_amount);//竞拍价格

                        //计算订单实际需支付费用custo_costs  getOrderActualPayment(auction_amount)
                        String custo_costs = getOrderActualPayment(auction_amount);
                        update.put("custo_costs",custo_costs);

                        //发送邮件竞拍成功

                    }else{
                         /*
                            二.竞拍失败-【流拍】
                                获取竞拍数据 如果无人参与竞拍
                                    1.将订单状态修改为流拍
                         */
//                        System.err.println("订单(order_id:"+order_id+")竞拍时间结束:竞拍失败-流拍");
                        update.put("order_status",5);//将订单状态修改为流拍

                        //不用发送邮件-待管理员处理(需要管理员将流拍订单手动确定支付金额再发送邮件通知游客)

                    }
                    //更新订单数据
                    daoSupport.update(mapper+"edit", update);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            //关闭
            ScheduledFuture scheduledFuture = Bus4uApplication.map.get(threadName);
            scheduledFuture.cancel(true);
            // 查看任务是否在正常执行之前结束,正常true
            boolean cancelled = scheduledFuture.isCancelled();
            while (!cancelled) {
                scheduledFuture.cancel(true);
            }

        }
    }

    /**
     * 计算订单实际支付价格(计算公式不明-待完善)
     * @param auction_amount 竞拍最低价格
     * @return 订单实际需支付费用custo_costs
     */
    private String getOrderActualPayment(String auction_amount){
        PageData currentUser = getCurrentUser();
        currentUser.get("guest_rate_discount");//利率折扣 会员等级 打折级别 折扣 默认1   100%  根据积分而来
        currentUser.get("cust_level");//会员等级名称

        return auction_amount;
    }
    @Override
    public int delete(Integer order_id) throws Exception {

        PageData pd = new PageData();
        pd.put("order_id",order_id);

        return (int) daoSupport.delete(mapper+"deleteById", pd);
    }

    @Override
    public int deleteAll(String[] DATA_IDS) throws Exception {
        return (int)daoSupport.batchDelete(mapper+"deleteAll", DATA_IDS);
    }



    @Override
    public List<PageData> list(PageData pd) throws Exception {
        //判断时间范围的搜索条件
//        System.err.println("OrderServiceImpl.list");

        if(pd.get("add_time_select") != null && !"".equals(pd.get("add_time_select"))){
            String add_time_select = pd.get("add_time_select").toString();
            String[] add_time_split = add_time_select.split(" - ");
            Date add_time_start = DateUtil.formatString(add_time_split[0], "yyyy-MM-dd HH:mm:ss");
            Date add_time_end = DateUtil.formatString(add_time_split[1], "yyyy-MM-dd HH:mm:ss");
            pd.put("add_time_start",add_time_start);
            pd.put("add_time_end",add_time_end);

        }
        //order_status订单状态
        if(pd.get("order_status") == null || "".equals(pd.get("order_status"))){
            pd.remove("order_status");

        }
        if(pd.get("contact_name_keys") == null || "".equals(pd.get("contact_name_keys"))){
            pd.remove("contact_name_keys");

        }

        List<PageData> list = (List<PageData>) daoSupport.findForList(mapper+"list",pd);
        Integer order_id;
        //遍历每个订单 获取订单ID 查询竞拍表获取每个订单的竞拍数据
        for (int i = 0; i < list.size(); i++) {
            order_id = Integer.parseInt(list.get(i).get("order_id").toString());
            List<PageData> auctionList = (List<PageData>) daoSupport.findForList("AuctionMapper.findById",order_id);
            list.get(i).put("auctionList",auctionList);

            Integer order_status2 = list.get(i).getInt("order_status");
            String order_status1 = getOrderStatusNameByCode(order_status2);
            list.get(i).put("order_status_name",order_status1);
        }

        return list;
    }

    @Override
    public PageData findById(Integer order_id) throws Exception {
        PageData pd = new PageData();
        pd.put("order_id",order_id);
        PageData pdObj = (PageData) daoSupport.findForObject(mapper+"findById", pd);
        log.info("=========================================");
        System.err.println("pdObj = " + pdObj);
        ArrayList arrayList = new ArrayList();
        if(pdObj != null && pdObj.get("stop1")!=null){
            Map<String,Object> map1 = new HashMap<String,Object>();
            map1.put("stop",pdObj.get("stop1"));
            arrayList.add(map1);
            if(pdObj.get("stop2")!=null){
                Map<String,Object> map2 = new HashMap<String,Object>();
                map2.put("stop",pdObj.get("stop2"));
                arrayList.add(map2);
                if(pdObj.get("stop3")!=null){
                    Map<String,Object> map3 = new HashMap<String,Object>();
                    map2.put("stop",pdObj.get("stop3"));
                    arrayList.add(map3);
                    if(pdObj.get("stop4")!=null){
                        Map<String,Object> map4 = new HashMap<String,Object>();
                        map2.put("stop",pdObj.get("stop4"));
                        arrayList.add(map4);
                        if(pdObj.get("stop5")!=null){
                            Map<String,Object> map5 = new HashMap<String,Object>();
                            map2.put("stop",pdObj.get("stop5"));
                            arrayList.add(map5);
                        }
                    }
                }
            }
        }else{
            System.err.println("pdObj = " + pdObj);
            return pdObj;
        }
        pdObj.put("stop",arrayList);
        System.err.println("pdObj = " + pdObj);
        return pdObj;
    }


    /**
     * 通过用户id和 开始时间 与 结束时间的搜索条件查询，查询当前用户的订单列表
     * @param user_id
     * @return
     * @throws Exception
     */
    @Override
    public List<PageData> findByUserId(String user_id,String startTime,String endTime,Integer order_status) throws Exception {
        PageData pd = new PageData();
        pd.put("user_id",user_id);
        if(startTime != null && !"".equals(startTime)){
            Date start = DateUtil.formatString(startTime, "yyyy-MM-dd HH:mm:ss");
            pd.put("start",start);
        }
        if(endTime != null && !"".equals(endTime)){
            Date end = DateUtil.formatString(endTime, "yyyy-MM-dd HH:mm:ss");
            pd.put("end",end);
        }
        if(order_status != null ){
            pd.put("order_status",order_status);
        }
        List<PageData> list  = (List<PageData>) daoSupport.findForList(mapper+"findByStarAndEndTime",pd);
//        for(int i =0,l=list.size();i<l;i++){
//            ArrayList arrayList = new ArrayList();
//            if(list.get(i).get("stop1")!=null){
//                arrayList.add(list.get(i).get("stop1"));
//                if(list.get(i).get("stop2")!=null){
//                    arrayList.add(list.get(i).get("stop2"));
//                    if(list.get(i).get("stop3")!=null){
//                        arrayList.add(list.get(i).get("stop3"));
//                        if(list.get(i).get("stop4")!=null){
//                            arrayList.add(list.get(i).get("stop4"));
//                            if(list.get(i).get("stop5")!=null){
//                                arrayList.add(list.get(i).get("stop5"));
//                            }
//                        }
//                    }
//                }
//            }else {
//                continue;
//            }
//            list.get(i).put("stop",arrayList);
//        }
//        System.err.println("list = " + list);
        for(int i =0;i<list.size();i++){
            Integer order_status2 = list.get(i).getInt("order_status");
            String order_status1 = getOrderStatusNameByCode(order_status2);
            list.get(i).put("order_status_name",order_status1);

        }
//        System.err.println("list = " + list);
        return list;
    }




    public static List<PageData> orderStatusCodeList;
    /**
     * 到项目状态代码表status_code 中获取订单所有状态的数据
     */
    @Override
    public List<PageData> findOrderStatusCodeList() throws Exception {

        orderStatusCodeList  = (List<PageData>) daoSupport.findForList(mapper+"findOrderStatusCodeList");

        return orderStatusCodeList;
    }

    /**
     * 通过订单状态代码得到订单状态名称
     * @param order_status
     * @return
     */
    private String getOrderStatusNameByCode(Integer order_status) throws Exception {
        String OrderStatusName = "";
        if(orderStatusCodeList == null){
            orderStatusCodeList = findOrderStatusCodeList();
        }
        boolean find = false;
        for (int i = 0; i < orderStatusCodeList.size() && !find; i++) {
            if(order_status == orderStatusCodeList.get(i).getInt("code")){
                OrderStatusName = orderStatusCodeList.get(i).getString("name");
//                OrderStatusName = orderStatusCodeList.get(i).getString("details");
                find = true;
            }
        }
        return OrderStatusName;
    }

    /**
     * 通过订单id获取该订单的状态order_status
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public Integer findStatusById(Integer id) throws Exception {
        return findStatusByOrderId(id);
    }
    
    private Integer findStatusByOrderId(Integer order_id) throws Exception {
        PageData pageData = new PageData();
        pageData.put("order_id",order_id);
        int order_status = (int)daoSupport.findForObject(mapper+"findStatusById",pageData);
        return order_status;
    }
    
    
    /**
     * 确定订单竞拍成功的竞拍人
     *
     * 参数PageData中获取
     *      auction_id      竞拍ID
     *      order_id        订单ID
     *      custo_costs     游客需支付价格
     *
     *      将订单由【竞拍中】改为【待支付】
     *      游客待支付费用保存到订单中
     *      修改竞拍ID 竞拍成功
     * @param pd
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public void confirmAuction(PageData pd) throws Exception {
        String auction_id = pd.getString("auction_id");
        Integer order_id = pd.getInt("order_id");
        double custo_costs = Double.parseDouble(pd.getString("custo_costs"));
        Integer order_status = findStatusByOrderId(order_id);
        if(order_status != 4){//如果订单状态不是竞拍中 说明有其他管理员修改了订单 或 系统自动走了竞拍完成流程
            throw new ServiceException("更新失败:请刷新页面确认订单状态是否为【竞拍中】");
        }
        //执行更新auction表前 需将该订单下的所有竞拍数据has_success重置为0 避免重复确认竞拍成功人的bug  clearAuctionSuccess
        auctionService.clearAuctionSuccess(order_id);
        pd.put("order_status",6);
        pd.put("has_success",1);
        int a = (int)daoSupport.update(mapper+"edit", pd);
        int b = (int)daoSupport.update("AuctionMapper.edit", pd);
        if(a != 1 || b != 1){
            throw new ServiceException("OrderServiceImpl.confirmAuction:更新失败!");
        }

    }




    /**
     * 到项目状态代码表status_code 中获取用户会员等级cust_level数据
     * @return
     * @throws Exception
     */
    @Override
    public List<PageData> findUserCustLevelCodeList() throws Exception {

        List<PageData> list  = (List<PageData>) daoSupport.findForList(mapper+"findUserCustLevelCodeList");

        return list;
    }

    @Override
    public String getEmailByOrderID(String order_id) throws Exception {
        if(order_id == null && StringUtils.isNotBlank(order_id)){
            throw new ServiceException("通过订单ID获取用户邮箱失败:order_id不能为空!");
        }
        String contact_email = (String)daoSupport.findForObject(mapper+"getContactEmailByOrderID", order_id);
        if(contact_email != null && StringUtils.isNotBlank(contact_email)){
            if(!EmailUtil.isEmail(contact_email)){
                throw new ServiceException("用户邮箱格式不正确!userEmail="+contact_email);
            }
        }else {
            throw new ServiceException("用户邮箱不正确!userEmail="+contact_email);
        }
        return contact_email;
    }

    /**
     * 验证订单必填项数据
     * @param pd
     */
    private void checkUserInfo(PageData pd){
        if( pd.get("passengers") ==null ||"".equals(pd.get("passengers").toString())){
            throw new ServiceException("订单创建失败:订单游客人数passengers不能空");
        }
        if(pd.get("time_depart") ==null || "".equals(pd.get("time_depart").toString())  ){
            throw new ServiceException("订单创建失败:启程时间time_depart不能空");
        }
        if(pd.get("fromwhere") ==null || "".equals(pd.get("fromwhere").toString())  ){
            throw new ServiceException("订单创建失败:出发地fromwhere不能空");
        }
        if( pd.get("towhere") ==null  || "".equals(pd.get("towhere").toString())){
            throw new ServiceException("订单创建失败:目的地towhere不能空");
        }
        if(pd.get("big_luggage") ==null|| "".equals(pd.get("big_luggage").toString()) ){
//            throw new ServiceException("订单创建失败:大件行李数量big_luggage不能空");
            pd.put("big_luggage",0);
        }
        if(pd.get("carry_luggage") ==null|| "".equals(pd.get("carry_luggage").toString()) ){
//            throw new ServiceException("订单创建失败:小件手提行李数量/随身行李carry_luggage不能空");
            pd.put("carry_luggage",0);
        }
        if(pd.get("babyseats_s") ==null|| "".equals(pd.get("babyseats_s").toString()) ){
//            throw new ServiceException("订单创建失败:婴儿座椅s:  4岁以下babyseats_s不能空");
            pd.put("babyseats_s",0);
        }
        if(pd.get("babyseats_b") ==null|| "".equals(pd.get("babyseats_b").toString()) ){
//            throw new ServiceException("订单创建失败:婴儿座椅b:  4岁以上babyseats_b不能空");
            pd.put("babyseats_b",0);
        }

        if(pd.get("WH_with") ==null|| "".equals(pd.get("WH_with").toString()) ){
//            throw new ServiceException("订单创建失败:折叠轮椅数量WH_with不能空");
            pd.put("WH_with",0);
        }
        if(pd.get("WH_OnBoard") ==null|| "".equals(pd.get("WH_OnBoard").toString()) ){
//            throw new ServiceException("订单创建失败:轮椅数量(不能折叠的)WH_OnBoard不能空");
            pd.put("WH_OnBoard",0);
        }
        //司机餐和住宿字段Driver_DM(Y/N)
        if(pd.get("driver_DM") ==null|| "".equals(pd.get("driver_DM").toString()) ){
//            throw new ServiceException("订单创建失败:司机餐和住宿driver_DM不能空");
            pd.put("driver_DM",0);
        }else{
            pd.put("driver_DM",1);
        }
        //是否有通行费(Y/N)
        if(pd.get("toll") ==null|| "".equals(pd.get("toll").toString()) || "N".equals(pd.get("GST").toString()) ){
            pd.put("toll",0);
        }else{
            pd.put("toll",1);
        }
        //消费税 Y/N  选中Y的话,则价格乘以1.1
        if(pd.get("GST") ==null|| "".equals(pd.get("GST").toString()) || "N".equals(pd.get("GST").toString()) ){
            pd.put("GST",0);
        }else{
            pd.put("GST",1);
        }
        //是否需要拖车(Y/N)
        if(pd.get("trailer") ==null|| "".equals(pd.get("trailer").toString()) || "N".equals(pd.get("trailer").toString()) ){
            pd.put("trailer",0);
        }else{
            pd.put("trailer",1);
        }
        //Airport Parking Fee 机场停车费(Y/N)
        if(pd.get("APF") ==null|| "".equals(pd.get("APF").toString()) || "N".equals(pd.get("APF").toString()) ){
            pd.put("APF",0);
        }else{
            pd.put("APF",1);
        }
        //National Park Entry Fee 国家公园门票(Y/N)
        if(pd.get("NPEF") ==null|| "".equals(pd.get("NPEF").toString()) || "N".equals(pd.get("NPEF").toString()) ){
            pd.put("NPEF",0);
        }else{
            pd.put("NPEF",1);
        }


        if(pd.get("order_type") ==null|| "".equals(pd.get("order_type").toString()) ){
            throw new ServiceException("订单创建失败:订单类型order_type不能空");
        }
    }



    /**
     * 新增订单填入默认值
     * @param pd
     * @return
     */
    private PageData addOrderDefaultValue(PageData pd) {
        //获取当前登录用户数据
        PageData currentUser = getCurrentUser();

//        pd.put("order_id", UuidUtil.get32UUID());
        pd.put("order_prefix_name","bus4u#");
        pd.put("user_id",getCurrentUserID());
        pd.put("order_status",0);
        pd.put("order_status_name","Waiting");
        pd.put("contact_name",currentUser.get("avatar"));
        pd.put("contact_phone",currentUser.get("phone"));
        pd.put("contact_email",currentUser.get("user_email"));
        pd.put("add_time",new Date());

        return pd;
    }

    /**
     * 获取当前登录用户数据
     * @return
     */
    private PageData getCurrentUser() {
        return (PageData) SecurityUtils.getSubject().getSession().getAttribute("currentUser");
    }
    private String getCurrentUserID(){
        PageData pd = (PageData) SecurityUtils.getSubject().getSession().getAttribute("currentUser");
        String user_id = pd.get("user_id").toString();
        return user_id;
    }

}
